﻿//er图控件
$(document).ready(function () {
    //var winId = 0;
    var methods = null;
    var isDown = false;
    var downItem = null;
    var curItem = null;
    var itemSp = null;
    var blackLine = "rgba(0,0,0,1)";
    var redLine = "rgba(255,0,0,1)";
    var isdrag = false;
    $.fn.er = function (method, args) {
        var er = this;
        return $.controlInit("er", er, method, args);

    };
    //控件默认值
    $.fn.er.defaultOption = {
        width: 800,
        height: 600,
        borderWidth: 1,
        borderColor: "#ff0000",
        drawLineabled: true
    };
    //控件默认值
    $.fn.er.defaultWinOption = {
        width: 130,
        height: 250,
        closed: false,
        closable: true,
        shadow: false,
        modal: false,
        checkbox: false,
        title: "新建窗体",
        top: 0,
        left: 0,
        list: []
    };
    //清空画布
    function clearCanvas(context) {
        var canvas = $(context.canvas);
        context.clearRect(0, 0, canvas.outerWidth(), canvas.outerHeight());
    }
    //获取画布
    function getCanvas(er, isTemp) {
        if (isTemp) {
            return er.data("canvasTemp");
        }
        else {
            return er.data("canvas");
        }
    };
    //获取画布上下文对象
    function getCanvasContext(er, isTemp) {
        var canvas = getCanvas(er, isTemp);
        if (canvas.length > 0) {
            var context = canvas.get(0).getContext("2d");
            return context;
        }
        return null;
    };

    //添加列表项事件
    function addEvent(item) {
        var movepixel = 5;
        item.bind("mousedown", function (evt) {
            if (evt.which == 1) {
                isDown = true;
                itemSp = { x: evt.pageX, y: evt.pageY };
                downItem = item;
            }
            $.emptySelected();
        })
        item.bind("mousemove", function (evt) {
            if (isDown) {
                var t = evt.target;
                if (t.tagName == "SPAN" || t.tagName == "INPUT") {
                    t = t.parentNode;
                }
                if (itemSp && (downItem && t == downItem.get(0))) {
                    var x = evt.pageX;
                    var y = evt.pageY;
                    if (Math.abs(itemSp.x - x) > 2 || Math.abs(itemSp.y - y) > 2) {
                        curItem = item;
                    }
                }
            }
            $.emptySelected();
        });
    }
    //添加窗口
    function addTable(er, window) {
        er.data("windows").push(window);
    }
    //重新绘制当前窗口的相关连线
    function redrawWindowLine(er, window, context) {
        var lines = methods.getLinesByTable(er, window);
        var alllines = methods.getAllLines(er);
        var temp = [];
        for (var i = 0; i < alllines.length; i++) {
            var line = alllines[i];
            if ($.inArray(line, lines) < 0 && $.inArray(line, temp) < 0) {
                temp.push(line);
            }
        }
        clearCanvas(context);
        mappingLines(er, context, temp, false);
        for (var i = 0; i < lines.length; i++) {
            var line = lines[i];
            if (line.selected) {
                lineStyle(context, 1, redLine);
            }
            else {
                lineStyle(context, 1, blackLine);
            }
            var fitem = line.fromItem;
            var titem = line.toItem;
            var newline = drawMLine(er, context, fitem.target, titem.target, true);
            if (newline) {
                line.point = newline.point;
                newline = null;
            }
        }
    }

    //添加一条线
    function addLine(er, context, fromItem, toItem) {
        var lines = fromItem.data("lines");
        //查询是否已经有连线
        var index = $.inArrayEx({ fromItem: fromItem, toItem: toItem }, lines, function (val, arrayValue) {
            var l = arrayValue;
            var fi = l.fromItem.target;
            var ti = l.toItem.target;
            if (fi.get(0) == val.fromItem.get(0) && ti.get(0) == val.toItem.get(0)) {
                return true;
            }
            return false;
        });
        if (index >= 0) {
            return;
        }
        lineStyle(context, 1, blackLine);
        var line = drawMLine(er, context, fromItem, toItem, true);
        var fobj = methods.getItemObject(er, fromItem);
        var tobj = methods.getItemObject(er, toItem);
        line.fromItem = fobj;
        line.toItem = tobj;
        line.caption = "";
        fromItem.data("lines").push(line);
        toItem.data("lines").push(line);
        fromItem.data("toItems").push(toItem);
        toItem.data("fromItems").push(fromItem);
        return line;
    }
    //设置线样式
    function lineStyle(context, lineWidth, color) {
        context.lineWidth = lineWidth;
        context.strokeStyle = color;
        context.fillStyle = color;
        //context.lineJoin = "round";
    }
    ////判断鼠标是否在线上
    function pointInLine(p, sp, ep) {
        var xlen = 0;
        var ylen = 0;
        var len1 = 0; //sp到p的距离
        var len2 = 0; //ep到p的距离
        var len3 = 0; //sp到ep的距离

        xlen = Math.abs(Math.pow(sp.x - p.x, 2));
        ylen = Math.abs(Math.pow(sp.y - p.y, 2));
        len1 = Math.sqrt(xlen + 好ylen);

        xlen = Math.abs(Math.pow(ep.x - p.x, 2));
        ylen = Math.abs(Math.pow(ep.y - p.y, 2));
        len2 = Math.sqrt(xlen + ylen);

        xlen = Math.abs(Math.pow(ep.x - sp.x, 2));
        ylen = Math.abs(Math.pow(ep.y - sp.y, 2));
        len3 = Math.sqrt(xlen + ylen);
        var tmp = (len1 + len2) - len3 //Math.round((len1 + len2)) - Math.round(len3);
        if (tmp < 0.1) {
            return true;
        }
        return false;
    }
    //画线
    function drawMLine(er, context, fromItem, toItem, isArrow, mouse) {
        if (!fromItem) {
            return null;
        }
        var fromOffset = fromItem.offset();
        var toOffset = null;
        if (toItem) {
            toOffset = toItem.offset();
        }
        var canvas = $(context.canvas);
        var windowBorder = 7;
        var length = 20;
        var offset = canvas.offset();
        var fsp = null, fep = null;
        var tsp = null, tep = null;
        var fromWindow = fromItem.data("window");

        var fscrollLeft = fromWindow.scrollLeft();
        fromOffset.left += fscrollLeft;

        if (toItem) {
            var toWindow = toItem.data("window");
            var tscrollLeft = toWindow.scrollLeft();
            toOffset.left += tscrollLeft;
        }

        if (toItem) {
            fsp = { x: fromOffset.left + fromWindow.innerWidth() + windowBorder, y: fromOffset.top + fromItem.innerHeight() / 2 };
            if (fromOffset.left + (fromWindow.innerWidth() / 2) > toOffset.left) {
                fsp.x = fromOffset.left - windowBorder;
            }
            //滚动条 start================
            if (fsp.y < fromWindow.offset().top) {
                fsp.y = fromWindow.offset().top;
            }
            else if (fsp.y > fromWindow.offset().top + fromWindow.innerHeight()) {
                fsp.y = fromWindow.offset().top + fromWindow.innerHeight();
            }
            //滚动条 end===========
            fsp.x -= offset.left;
            fsp.y -= offset.top;
            var fep = { x: fsp.x + length, y: fsp.y };
            if (fromOffset.left + (fromWindow.innerWidth() / 2) > toOffset.left) {
                fep.x = fsp.x - length;
            }

            tsp = { x: toOffset.left - windowBorder - length, y: toOffset.top + toItem.innerHeight() / 2 };
            if (toOffset.left + (toWindow.innerWidth() / 2) < fromOffset.left) {
                tsp.x = toOffset.left + toWindow.innerWidth() + windowBorder + length;
            }
            //滚动条 start================
            if (tsp.y < toWindow.offset().top) {
                tsp.y = toWindow.offset().top;
            }
            else if (tsp.y > toWindow.offset().top + toWindow.innerHeight()) {
                tsp.y = toWindow.offset().top + toWindow.innerHeight();
            }
            //滚动条 end===========
            tsp.x -= offset.left;
            tsp.y -= offset.top;
            tep = { x: tsp.x + length, y: tsp.y };
            if (toOffset.left + (toWindow.innerWidth() / 2) < fromOffset.left) {
                tep.x = tsp.x - length;
            }

        }
        else {
            if (mouse) {
                fsp = { x: fromOffset.left + fromWindow.innerWidth() + windowBorder, y: fromOffset.top + fromItem.innerHeight() / 2 };
                if (mouse.x < (fromOffset.left + fromWindow.innerWidth() / 2)) {
                    fsp.x = fromOffset.left - windowBorder;
                }
                fsp.x -= offset.left;
                fsp.y -= offset.top;
                var fep = { x: fsp.x + length, y: fsp.y };
                if (mouse.x < (fromOffset.left + fromWindow.innerWidth() / 2)) {
                    fep.x = fsp.x - length;
                }
                tsp = { x: mouse.x - length, y: mouse.y };
                if (mouse.x < (fromOffset.left + fromWindow.innerWidth() / 2)) {
                    tsp = { x: mouse.x + length, y: mouse.y };
                }
                tsp.x -= offset.left;
                tsp.y -= offset.top;
                tep = { x: tsp.x + length, y: tsp.y };
                if (mouse.x < (fromOffset.left + fromWindow.innerWidth() / 2)) {
                    tep = { x: tsp.x - length, y: tsp.y };
                }
            }
        }
        var line = { point: [] };
        context.beginPath();
        context.moveTo(fsp.x, fsp.y);
        line.point.push(fsp);
        context.lineTo(fep.x, fep.y);
        line.point.push(fep);
        context.lineTo(tsp.x, tsp.y);
        line.point.push(tsp);
        context.lineTo(tep.x, tep.y);
        line.point.push(tep);
        context.stroke();
        context.closePath();
        if (isArrow) {
            //drawArrowHead(fep, fsp, 10, 30, context);
            drawArrowHead(tsp, tep, 10, 30, context);
        }
        return line;
    }
    //删除线
    function removeLine(er, args) {
        var fitem = args.fromItem;
        var titem = args.toItem;
        var flines = fitem.data("lines");
        var tlines = titem.data("lines");
        var index1 = [];
        for (var i = 0; i < flines.length; i++) {
            var l = flines[i];
            var f = l.fromItem.target;
            var t = l.toItem.target;
            if (f.get(0) == fitem.get(0) && t.get(0) == titem.get(0)) {
                index1.push(i);
            }
        }
        var index2 = [];
        for (var i = 0; i < tlines.length; i++) {
            var l = tlines[i];
            var f = l.fromItem.target;
            var t = l.toItem.target;
            if (f.get(0) == fitem.get(0) && t.get(0) == titem.get(0)) {
                index2.push(i);
            }
        }

        //删除item之间的关系 start======================
        for (var i = 0; i < index1.length; i++) {
            var idx = index1[i];
            var l = flines[idx];
            var fitem = l.fromItem.target;
            var titem = l.toItem.target;
            var toItems = fitem.data("toItems");
            var itemIndex = $.inArrayEx(titem, toItems, function (v1, v2) {
                return v1.get(0) == v2.get(0);
            });
            if (itemIndex >= 0) {
                toItems.splice(itemIndex, 1);
            }
        }
        for (var i = 0; i < index2.length; i++) {
            var idx = index2[i];
            var l = tlines[idx];
            var fitem = l.fromItem.target;
            var titem = l.toItem.target;
            var fromItems = titem.data("fromItems");
            var itemIndex = $.inArrayEx(fitem, fromItems, function (v1, v2) {
                return v1.get(0) == v2.get(0);
            });
            if (itemIndex >= 0) {
                fromItems.splice(itemIndex, 1);
            }
        }
        //删除item之间的关系 end======================

        for (var i = 0; i < index1.length; i++) {
            var idx = index1[i];
            if (idx >= 0) {
                flines.splice(idx, 1);
            }
        }
        for (var i = 0; i < index2.length; i++) {
            var idx = index2[i];
            if (idx >= 0) {
                tlines.splice(idx, 1);
            }
        }
    }

    //判断鼠标是否在线上
    function pointInLine(p, sp, ep) {
        var xlen = 0;
        var ylen = 0;
        var len1 = 0; //sp到p的距离
        var len2 = 0; //ep到p的距离
        var len3 = 0; //sp到ep的距离

        xlen = Math.abs(Math.pow(sp.x - p.x, 2));
        ylen = Math.abs(Math.pow(sp.y - p.y, 2));
        len1 = Math.sqrt(xlen + ylen);

        xlen = Math.abs(Math.pow(ep.x - p.x, 2));
        ylen = Math.abs(Math.pow(ep.y - p.y, 2));
        len2 = Math.sqrt(xlen + ylen);

        xlen = Math.abs(Math.pow(ep.x - sp.x, 2));
        ylen = Math.abs(Math.pow(ep.y - sp.y, 2));
        len3 = Math.sqrt(xlen + ylen);
        var tmp = (len1 + len2) - len3 //Math.round((len1 + len2)) - Math.round(len3);
        if (tmp < 0.1) {
            return true;
        }
        return false;
    }

    //画箭头
    function drawArrowHead(start, end, arrowLength, arrowAngle, context) {
        var startX = start.x;
        var startY = start.y;
        var endX = end.x;
        var endY = end.y;
        var lineAngle = null;
        //线角度
        if (endX - startX != 0) {
            lineAngle = Math.atan((endY - startY) / (endX - startX));
        }
        else {
            if (endY - startY < 0)//方向向上
                lineAngle = Math.PI / 2;
            else//方向向下
                lineAngle = 3 * Math.PI / 2;
        }
        if (endY - startY >= 0 && endX - startX <= 0) {
            lineAngle = lineAngle + Math.PI;
        } else if (endY - startY <= 0 && endX - startX <= 0) {
            lineAngle = lineAngle + Math.PI;
        }
        var arrowA = arrowAngle / 2;
        var arrowB = arrowAngle / 2;
        var arrowRadians1 = arrowA * Math.PI / 180;
        var arrowRadians2 = arrowB * Math.PI / 180; //箭头夹角弧度
        var arrowRadians = arrowAngle * Math.PI / 180;

        var lineA = lineAngle * 180 / Math.PI;
        var line1 = arrowLength / Math.cos(arrowRadians1);
        var temp = lineA + arrowA;
        var offsetX = line1 * Math.cos(temp * Math.PI / 180);
        var offsetY = line1 * Math.sin(temp * Math.PI / 180);
        var px1 = end.x - offsetX;
        var py1 = end.y - offsetY;
        context.moveTo(end.x, end.y);
        context.lineTo(px1, py1);

        var temp1 = lineA - arrowB;
        var offsetX1 = line1 * Math.cos(temp1 * Math.PI / 180);
        var offsetY1 = line1 * Math.sin(temp1 * Math.PI / 180);
        var px2 = end.x - offsetX1;
        var py2 = end.y - offsetY1;
        context.beginPath();
        context.moveTo(end.x, end.y);
        context.lineTo(px2, py2);
        context.lineTo(px1, py1);
        context.stroke();
        context.closePath();
        context.fill();
        context.closePath();
    }

    //映射数组里的线
    function mappingLines(er, context, lines, isclear) {
        if (isclear) {
            clearCanvas(context);
        }
        var selectLines = [];
        for (var i = 0; i < lines.length; i++) {
            var line = lines[i];
            if (!line.selected) {
                lineStyle(context, 1, blackLine);
                context.beginPath();
                for (var n = 0; n < line.point.length; n++) {
                    var point = line.point[n];
                    if (n == 0) {
                        context.moveTo(point.x, point.y);
                    }
                    else {
                        context.lineTo(point.x, point.y);
                    }
                }
                context.stroke();
                context.closePath();
                //drawArrowHead(line.point[1], line.point[0], 10, 30, context);
                drawArrowHead(line.point[2], line.point[3], 10, 30, context);
            }
            else {
                selectLines.push(line);
            }
        }
        //画被选中的线
        for (var i = 0; i < selectLines.length; i++) {
            var line = selectLines[i];
            lineStyle(context, 1, redLine);
            context.beginPath();
            for (var n = 0; n < line.point.length; n++) {
                var point = line.point[n];
                if (n == 0) {
                    context.moveTo(point.x, point.y);
                }
                else {
                    context.lineTo(point.x, point.y);
                }
            }
            context.stroke();
            context.closePath();
            //drawArrowHead(line.point[1], line.point[0], 10, 30, context);
            drawArrowHead(line.point[2], line.point[3], 10, 30, context);
        }
    }
    function createItemInnerHTML(er, item) {
        var itemDiv = $("#item_" + item.fieldId);
        itemDiv.html("");
        if (item.checkbox) {
            check = $("<input style='vertical-align:middle;' type='checkbox' value='" + item.field + "' id='chk_" + item.fieldId + "'/>");
            if (item.checked) {
                check.attr("checked", "checked");
            }
            check.bind("click", function (evt) {
                var checkbox = $(evt.currentTarget);
                var it = checkbox.closest(".item");
                if (checkbox.attr("checked")) {
                    methods.itemSelected(er, it);
                }
                else {
                    methods.itemUnSelected(er, it);
                }
                evt.stopPropagation();
            });
            check.appendTo(itemDiv);
        }
        var text = "";
        if (item.text && item.field) {
            text = item.text + "(" + item.field + ")";
        }
        else if (item.text && !item.field) {
            text = item.text; //
        }
        else if (!item.text && item.field) {
            text = item.field;
        }
        var span = $("<span>" + text + "</span>").appendTo(itemDiv);
        if (item.iconCls) {
            span.css("paddingLeft", "20px");
            span.css("backgroundPosition", "left");
            span.addClass(item.iconCls);
        }
        span.addClass("ellipsis");
    }
    function addItem(er, div, items) {
        //var options = methods.options(er);
        var listBox = div.find(".itemBox");
        if (listBox.length <= 0) {
            listBox = $("<div class='itemBox' style='width:100%;overflow-x;hide;'/>").appendTo(div);
        }
        listBox.html("");
        //listBox.width(div.width());
        var wobj = methods.getTableObject(er, div);
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var itemDiv = $("<div id='item_" + item.fieldId + "' fieldid='" + item.fieldId + "' field='" + item.field + "'></div>").appendTo(listBox) //+ check+
            createItemInnerHTML(er, item);
            item.target = itemDiv;
            itemDiv.addClass("item");
            itemDiv.css("width", wobj.width);
            itemDiv.width("100%");
            itemDiv.addClass("ellipsis");
            itemDiv.attr("title", item.text + "(" + item.field + ")");
            itemDiv.data("itemObject", item);
            itemDiv.data("toItems", []);
            itemDiv.data("fromItems", []);
            itemDiv.data("itemObject", item);
            div.data("items").push(itemDiv);
        }
        listBox.children("div.item").each(function (i) {
            var item = $(this);
            item.data("window", div);
            item.data("lines", []);

            item.hover(function () {
                item.addClass("itemSelect");
            }, function () {
                item.removeClass("itemSelect");
            });
            addEvent(item);
        });
        wobj.items = items;
    }

    //删除表
    function removeTable(er, args) {
        var win = args;
        var options = methods.options(er);
        var lines = methods.getLinesByTable(er, win);

        for (var i = 0; i < lines.length; i++) {
            var line = lines[i];
            var fitem = line.fromItem.target;
            var titem = line.toItem.target;
            removeLine(er, { fromItem: fitem, toItem: titem });
            //methods.removeLine(er, { fromItem: fitem, toItem: titem });
        }
        var wins = methods.getAllTables(er);
        var i = wins.length - 1;
        while (i >= 0) {
            var w = wins[i];
            if (w && (w.get(0) == win.get(0))) {
                wins.splice(i, 1);
            }
            i--;
        }
        lines = methods.getAllLines(er);
        var context = getCanvasContext(er, false);
        mappingLines(er, context, lines, true);
        if (options.onRemoveWindowAfter) {
            options.onRemoveWindowAfter(er, win, lines);
        }
    }

    //公开函数
    $.fn.er.methods = {
        init: function (er, args) {
            methods = $.fn.er.methods;
            er.each(function (i) {
                var e = er.eq(i);
                var opts = $.extend({}, $.fn.er.defaultOption, args);
                e.data("options", opts);
                e.data("winId", 0);

                e.addClass("er");
                e.css("overflow", "auto");
                e.css("position", "relative");
                methods.draw(e, args);
            });
        },
        options: function (er, args) {
            return er.data("options");
        },
        draw: function (er, args) {
            var options = methods.options(er);
            var w = options.width; //-(options.borderWidth * 2);
            var h = options.height; // -(options.borderWidth * 2);
            if (options.fit) {

                w = er.parent().width();
                h = er.parent().height();
                //alert(w + "," + h)
            }
            if ($.support.boxModel) {
                w -= (options.borderWidth * 2);
                h -= (options.borderWidth * 2);
                //alert(w + "," + h)
            }
            er.width(w).height(h);
            if (options.borderWidth > 0) {
                er.css("border", options.borderWidth + "px " + options.borderColor + " solid");
            }
            //alert("a")
            var c = document.createElement("canvas");
            var ctemp = document.createElement("canvas");
            er.get(0).appendChild(c);
            er.get(0).appendChild(ctemp);
            var canvas = $(c);
            var canvas1 = $(ctemp);
            canvas.attr({ "width": w, "height": h });
            canvas1.attr({ "width": w, "height": h });
            canvas.css({ "position": "absolute" });
            canvas1.css({ "position": "absolute", "zIndex": 99 });

            if ($.browser.msie && parseFloat($.browser.version) < 9) {
                window.G_vmlCanvasManager.initElement(c);
                window.G_vmlCanvasManager.initElement(ctemp);
            }
            //var canvas = $("<canvas width=\"" + w + "\" height=\"" + h + "\" style=\"position:absolute;\"></canvas>").appendTo(er);  //您的浏览器不支持CANVAS标签，推荐使用最新版本的Firefox或Chrome浏览器absolute
            //var canvas1 = $("<canvas width=\"" + w + "\" height=\"" + h + "\" style=\"position:absolute;z-index:99\"></canvas>").appendTo(er);
            //er.width(options.width + (options.borderWidth * 2)).height(options.height + (options.borderWidth * 2));
            er.data("canvas", canvas);
            er.data("isDrawLine", false);
            er.data("canvasTemp", canvas1);
            er.data("windows", []);
            er.data("canvasSize", { width: w, height: h });
            er.bind("selectstart", function (evt) { return false; });
            er.css("-moz-user-select", "none");
            var captionbox = $("<div class=\"captionbox\" style=\"position:absolute;display:none;z-index:99999;\"></div>").appendTo(er);

            var toItem = null;
            var fromItem = null;
            var hoverLine = null;
            var selectLine = null;
            var hoverWin = null;
            er.bind("contextmenu", function (evt) {
                try {
                    if (hoverLine) {
                        if ($.isFunction(options.onLineContextmenu)) {
                            options.onLineContextmenu(er, hoverLine, evt);
                        }
                    }
                    else {
                        var jq = $(evt.target);
                        if (jq.hasClass("panel-title")) {
                            if ($.isFunction(options.onWindowContextmenu) || $.isFunction(options.onTableContextmenu)) {
                                var win = jq.parent().next();
                                var wobj = methods.getTableObject(er, win);
                                if ($.isFunction(options.onWindowContextmenu)) {
                                    options.onWindowContextmenu(er, wobj, evt);
                                }
                                else if ($.isFunction(options.onTableContextmenu)) {
                                    options.onTableContextmenu(er, wobj, evt);
                                }
                            }
                        }
                        else if (jq.closest("div.item").length > 0 || jq.hasClass("item")) {
                            if ($.isFunction(options.onItemContextmenu)) {
                                var item = jq.hasClass("item") ? jq : jq.closest("div.item");
                                item = methods.getItemObject(er, item);
                                options.onItemContextmenu(er, item, evt);
                            }
                        }
                        //                        if (evt.target.tagName == "DIV") {
                        //                            //右键窗体时的事件
                        //                            var div = $(evt.target);
                        //                            if (div.hasClass("panel-title")) {
                        //                                if ($.isFunction(options.onWindowContextmenu) || $.isFunction(options.onTableContextmenu)) {
                        //                                    var win = div.parent().next();
                        //                                    var wobj = methods.getTableObject(er, win);
                        //                                    if ($.isFunction(options.onWindowContextmenu)) {
                        //                                        options.onWindowContextmenu(er, wobj, evt);
                        //                                    }
                        //                                    else if ($.isFunction(options.onTableContextmenu)) {
                        //                                        options.onTableContextmenu(er, wobj, evt);
                        //                                    }
                        //                                }
                        //                            }
                        //                        }
                    }
                }
                catch (ex) { }
                finally {
                    return false;
                }
            });
            er.bind("mousedown", function (evt) {
                if (evt.which == 1) {
                    isDown = true;
                    //document.title = "ermousedown" + evt.target.tagName;
                    $(document).bind("mousemove", mouseMoveHandler);
                    $(document).bind("mouseup", mouseUpHandler);
                    captionbox.hide();
                    evt.preventDefault();
                }
            });
            er.bind("mousemove", function (evt) {
                //$("#txt").val(evt.pageX + "," + evt.pageY);
                //window.status = isDown;
                if (!isDown) {
                    hoverLine = null;
                    hoverWin = null;
                    //window.status = evt.target.tagName;
                    //当触发事件的元素是CANVAS（或者兼容IE为具体包含在CANVAS下的子节点）
                    if (evt.target.tagName == "CANVAS" || ($.contains(canvas1.get(0), evt.target) || $.contains(canvas.get(0), evt.target))) {
                        var lines = methods.getAllLines(er);
                        var offset = er.offset();
                        for (var i = lines.length - 1; i >= 0; i--) {
                            var line = lines[i];
                            for (var n = 0; n < line.point.length - 1; n++) {
                                var p1 = line.point[n];
                                var p2 = line.point[n + 1];
                                if (pointInLine({ x: evt.pageX - offset.left + er.scrollLeft(), y: evt.pageY - offset.top + er.scrollTop() }, p1, p2)) {
                                    hoverLine = line;
                                    break;
                                }
                            }
                            if (hoverLine) {
                                break;
                            }
                        }

                    }
                    else {
                        if (evt.target.tagName == "DIV") {
                            var div = $(evt.target);
                            if (div.hasClass("panel-title")) {
                                hoverWin = div.parent().next();
                            }
                        }
                    }
                    if (hoverLine || hoverWin) {
                        if (hoverLine) {
                            var contextTemp = getCanvasContext(er, true);
                            clearCanvas(contextTemp);
                            lineStyle(contextTemp, 2, redLine);
                            drawMLine(er, contextTemp, hoverLine.fromItem.target, hoverLine.toItem.target, true);
                            if (hoverLine && hoverLine.caption) {
                                captionbox.html(hoverLine.caption);
                                var offset = er.offset();
                                var x = evt.pageX - offset.left + 10 + er.scrollLeft();
                                var y = evt.pageY - offset.top + 10 + er.scrollTop();
                                captionbox.css({ left: x, top: y }).show();
                            }
                        }
                        else if (hoverWin) {
                            var contextTemp = getCanvasContext(er, true);
                            clearCanvas(contextTemp);
                            var winObj = methods.getTableObject(er, hoverWin);
                            if (winObj.caption) {
                                captionbox.html(winObj.caption);
                                var offset = er.offset();
                                var x = evt.pageX - offset.left + 10 + er.scrollLeft();
                                var y = evt.pageY - offset.top + 10 + er.scrollTop();
                                //window.status = x + "," + y;
                                captionbox.css({ left: x, top: y }).show();
                            }
                        }
                    }
                    else {
                        var contextTemp = getCanvasContext(er, true);
                        clearCanvas(contextTemp);
                        captionbox.hide();
                    }
                }

            });
            function mouseUpHandler(evt) {
                //document.title = "ermouseup"
                var options = methods.options(er);
                try {
                    if (isDown) {
                        var contextTemp = getCanvasContext(er, true);
                        clearCanvas(contextTemp);
                        //画线
                        if (fromItem && toItem) {
                            if (options.drawLineabled) {
                                methods.addLine(er, { fromField: fromItem, toField: toItem });
                            }
                        }
                        //选中线
                        else if (hoverLine) {
                            var lines = methods.getAllLines(er);
                            for (var i = 0; i < lines.length; i++) {
                                lines[i].selected = false;
                            }
                            hoverLine.selected = true;
                            var context = getCanvasContext(er);
                            mappingLines(er, context, lines, true);
                            if ($.isFunction(options.onLineSelected)) {
                                options.onLineSelected(er, hoverLine);
                            }
                            //排斥选中窗体
                            var wins = methods.getAllTables(er);
                            for (var i = 0; i < wins.length; i++) {
                                var obj = wins[i].data("windowObject");
                                obj.selected = false;
                            }

                        }
                        //选中窗体
                        else if (hoverWin) {
                            if (!isdrag) {
                                var wins = methods.getAllTables(er);
                                for (var i = 0; i < wins.length; i++) {
                                    var obj = wins[i].data("windowObject");
                                    obj.selected = false;
                                }
                                var hoverWinObj = hoverWin.data("windowObject");
                                hoverWinObj.selected = true;

                                //排斥选中线
                                var lines = methods.getAllLines(er);
                                for (var i = 0; i < lines.length; i++) {
                                    lines[i].selected = false;
                                }
                                var context = getCanvasContext(er);
                                mappingLines(er, context, lines, true);
                                if ($.isFunction(options.onTableSelected)) {
                                    options.onTableSelected(er, hoverWinObj);
                                }
                                /*window.setTimeout(function () {
                                   
                                }, 100);*/
                            }
                        }
                    }
                    else {
                    }
                }
                catch (ex) {
                }
                finally {
                    $(document).unbind("mousemove", mouseMoveHandler);
                    $(document).unbind("mouseup", mouseUpHandler);
                    isDown = false;
                    itemSp = null;
                    curItem = null;
                    downItem = null;
                    toItem = null;
                    fromItem = null;
                    hoverLine = null;
                    hoverWin = null;
                    isdrag = false;
                    return false;
                }
            }
            function mouseMoveHandler(evt) {

                //document.title="ermousemove"
                if (isDown) {
                    //鼠标拖拽时滚动条自动滚动
                    if (evt.pageX < er.offset().left) {
                        er.scrollLeft(er.scrollLeft() - er.offset().left - evt.pageX);
                    }
                    if (evt.pageY < er.offset().top) {
                        er.scrollTop(er.scrollTop() - er.offset().top - evt.pageY);
                    }
                    var t = evt.target;
                    if (t.tagName == "SPAN" || t.tagName == "INPUT") {
                        t = t.parentNode;
                    }
                    if ((t.tagName == "DIV") && (curItem && (t != curItem.get(0)))) {
                        //如果设置允许画线
                        //toItem = null;
                        //fromItem = null;
                        if (options.drawLineabled) {
                            var item = $(t);
                            if (item.hasClass("item")) {
                                toItem = item;
                            }
                            if (toItem) {
                                if (curItem) {
                                    fromItem = curItem;
                                }
                                if (fromItem) {
                                    //画线
                                    if (toItem.data("window").get(0) != fromItem.data("window").get(0)) {
                                        var context = getCanvasContext(er, true);
                                        clearCanvas(context);
                                        lineStyle(context, 1, blackLine);
                                        drawMLine(er, context, fromItem, toItem, true);
                                    }
                                }
                            }
                            else {
                                var context = getCanvasContext(er, true);
                                clearCanvas(context);
                                lineStyle(context, 1, blackLine);
                                var mouse = { x: evt.pageX, y: evt.pageY };
                                if (curItem) {
                                    fromItem = curItem;
                                    //top.document.title = fromItem + "1";
                                }

                                drawMLine(er, context, fromItem, null, true, mouse);
                            }
                        }
                    }
                    else if (evt.target.tagName == "CANVAS") {
                        if (options.drawLineabled) {
                            var context = getCanvasContext(er, true);
                            clearCanvas(context);
                            lineStyle(context, 1, blackLine);
                            var mouse = { x: evt.pageX, y: evt.pageY };
                            if (curItem) {
                                fromItem = curItem;
                            }
                            //top.document.title = fromItem + "2";
                            drawMLine(er, context, fromItem, null, true, mouse);
                        }
                    }
                }
            }

        },
        //添加线
        addLine: function (er, args) {
            var options = methods.options(er);
            var fromItem = args.fromField;
            var toItem = args.toField;
            var context = getCanvasContext(er, false);
            var fromWindow = methods.getTableByItem(er, fromItem);
            var toWindow = methods.getTableByItem(er, toItem);

            if (fromWindow != toWindow) {
                var ismark = true;
                if ($.isFunction(options.onAddLineBefore)) {
                    var fi = methods.getItemObject(er, fromItem);
                    var ti = methods.getItemObject(er, toItem);
                    ismark = options.onAddLineBefore(er, fromWindow, toWindow, fi, ti);
                }
                if (ismark != false) {
                    var l = addLine(er, context, fromItem, toItem);
                    //画线后调用
                    if (l) {
                        if ($.isFunction(options.onAddLineAfter)) {
                            options.onAddLineAfter(er, l, args);
                        }
                        return l;
                    }
                }
            }
            return null;
        },
        //添加表
        addTable: function (er, args) {
            var options = methods.options(er);
            var winId = er.data("winId");
            winId++;
            var winArgs = $.extend({}, $.fn.er.defaultWinOption, args);
            if (!winArgs.alias) {
                winArgs.alias = winArgs.name; // +"_" + winId;
                while (!chkAlias(winArgs.alias)) {
                    winId++;
                    winArgs.alias = winArgs.name + "_" + winId;
                }
            }
            //验证别名是否重复
            function chkAlias(alias) {
                var wins = methods.getAllTables(er);
                if ($.isArray(wins)) {
                    for (var i = 0; i < wins.length; i++) {
                        var w = methods.getTableObject(er, wins[i]);
                        if (w) {
                            if (w.alias == alias) {
                                return false;
                            }
                        }
                    }
                }
                return true;
            }
            er.data("winId", winId);
            winArgs.code = winArgs.code || $.newGuid();
            var div = $("<div id='win_" + (winArgs.code) + "' code='" + winArgs.code + "' style='position:relative;overflow-x:hidden;'/>").appendTo(er);
            winArgs.top = parseInt(winArgs.top);
            winArgs.left = parseInt(winArgs.left);
            winArgs.title = winArgs.title || winArgs.name;
            winArgs.target = div;
            div.attr("name", winArgs.name); //表名
            div.attr("alias", winArgs.alias); //别名
            div.data("title", winArgs.title);
            div.data("windowObject", winArgs);
            div.data("left", winArgs.left);
            div.data("top", winArgs.top);
            div.data("items", []);
            addItem(er, div, winArgs.items);
            var icon = "icon-mydesktop";
            if (winArgs.iconCls) {
                icon = winArgs.iconCls;
            }
            if (winArgs.isMain) {
                var icon = "icon-tip";
            }
            div.window({
                title: winArgs.title,
                width: winArgs.width,
                height: winArgs.height,
                modal: winArgs.modal,
                shadow: winArgs.shadow,
                closed: winArgs.closed,
                caption: winArgs.caption,
                iconCls: icon,
                headerCls: "ellipsis",
                inline: true,
                collapsible: false,
                minimizable: false,
                maximizable: false,
                top: winArgs.top,
                left: winArgs.left,
                draggable: true,
                onMove: function (left, top) {
                    try {
                        var options = methods.options(er);
                        var parent = div.parent();
                        var erOffset = er.offset();
                        var l = left + er.scrollLeft();
                        var t = top + er.scrollTop();
                        var canvas = getCanvas(er, false);
                        var canvasTemp = getCanvas(er, true);
                        var isremove = false;
                        //如果超出最小边界重新定位
                        if (left < 0) {
                            isremove = true;
                            l = 0;
                        }
                        if (top < 0) {
                            isremove = true;
                            t = 0;
                        }
                        if (isremove) {
                            div.window("move", { left: l, top: t });
                            return;
                        }
                        var wins = methods.getAllTables(er);
                        var maxX = 0;
                        var maxY = 0;
                        var minX = er.data("canvasSize").width;
                        var minY = er.data("canvasSize").height;
                        for (var i = 0; i < wins.length; i++) {
                            var win = wins[i];
                            var winbox = win.parent();
                            var winopts = win.window("options");
                            var winleft = winopts.left + er.scrollLeft();
                            var wintop = winopts.top + er.scrollTop();
                            var x = winleft + winbox.outerWidth();
                            var y = wintop + winbox.outerHeight();
                            if (maxX < x) {
                                maxX = x;
                            }
                            if (maxY < y) {
                                maxY = y;
                            }
                        }
                        if (canvas.width() != maxX) {
                            var w = maxX;
                            if (w < minX) {
                                w = minX;
                            }
                            if (canvas.width() != w) {
                                canvas.attr("width", w);
                                canvasTemp.attr("width", w);
                            }
                        }
                        if (canvas.outerHeight() != maxY) {
                            var h = maxY;
                            if (h < minY) {
                                h = minY;
                            }
                            if (canvas.height() != h) {
                                canvas.attr("height", h);
                                canvasTemp.attr("height", h);
                            }
                        }
                        //alert(canvas.height())
                        var context = getCanvasContext(er, false);
                        redrawWindowLine(er, div, context);
                        if ($.isFunction(options.onTableMove)) {
                            options.onTableMove(er, winArgs, t, l);
                        }
                        winArgs.top = t;
                        winArgs.left = l;
                    }
                    catch (ex) {
                    }
                    finally {
                        if (div.data("top") != t || div.data("left") != l) {
                            div.data("top", t);
                            div.data("left", l);
                            isdrag = true;
                        }
                    }
                },
                onResize: function (width, height) {
                    var context = getCanvasContext(er, false);
                    redrawWindowLine(er, div, context);

                    var listbox = div.find(".itemBox");
                    //listbox.width(listbox.parent().width());
                    var items = div.find(".item");
                    items.width(listbox.parent().width())
                    if ($.support.boxModel) {
                        var w1 = items.width();
                        var w2 = items.outerWidth();
                        var w3 = w2 - w1;
                        items.width(w1 - w3);
                    }
                },
                onBeforeClose: function () {
                    if (options.onRemoveWindowBefore) {
                        var wobj = methods.getTableObject(er, div);
                        if (options.onRemoveWindowBefore(er, wobj) == false) {
                            return false;
                        }
                    }
                },
                onClose: function () {
                    removeTable(er, div);
                    div.window("destroy");
                }
            });
            addTable(er, div);
            if ($.isFunction(options.onAddTableAfter)) {
                options.onAddTableAfter(er, winArgs);
            }
            //滚动条事件
            div.bind("scroll", function (evt) {
                var context = getCanvasContext(er, false);
                redrawWindowLine(er, div, context);
            });
            var title = div.parent().find(".panel-title");
            title.addClass("ellipsis");
            return winArgs;
        },
        getTableObject: function (er, args) {
            var win = args;
            if (win) {
                try {
                    return win.data("windowObject");
                }
                catch (ex) {
                    var d = 0;
                }
            }
            return null;
        },
        getTableByCode: function (er, args) {
            //var div = er.find("div[code=" + args + "]");
            var div = $("#win_" + args);
            return div;
        },
        getTableCode: function (er, args) {
            var win = args;
            if (win instanceof jQuery) {
                return win.attr("code");
            }
            else if (typeof (win) == "object") {
                if (win.code) {
                    return win.code;
                }
            }
            return null;
        },

        //获取窗体相关的线
        getLinesByTable: function (er, args) {
            var items = args.data("items");
            var temp = [];
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                //alert(item.text);
                var lines = item.data("lines");
                if (lines) {
                    for (var n = 0; n < lines.length; n++) {
                        if ($.inArray(lines[n], temp) < 0) {
                            temp.push(lines[n]);
                        }
                    }
                }
            }
            return temp;
        },
        //获取当前字段有多少入线
        getFromLinesByItem: function (er, args) {
            var item = args;
            var temp = [];
            var lines = item.data("lines");
            $.loop(lines, function (v, i) {
                if (v.toItem.target.get(0) == item.get(0)) {
                    temp.push(v);
                }
            });
            return temp;
        },
        //获取当前字段的出线
        getToLineByItem: function (er, args) {
            var item = args;
            var temp = [];
            var lines = item.data("lines");
            $.loop(lines, function (v, i) {
                if (v.fromItem.target.get(0) == item.target.get(0)) {
                    temp.push(v);
                }
            });
            return temp;
            //            fromItem.data("toItems").push(toItem);
            //            toItem.data("fromItems").push(fromItem);
        },
        //获取窗体相关的出线
        getToLinesByTable: function (er, args) {
            var table = args;
            var tObject = methods.getTableObject(er, table);
            var lines = methods.getLinesByTable(er, table);
            if (lines) {
                var temp = [];
                for (var i = 0; i < lines.length; i++) {
                    var l = lines[i];
                    var fromItem = l.fromItem;
                    if (checkToTableIsSelf(fromItem.target)) {
                        temp.push(l);
                    }
                }
                return temp;
            }
            return [];
            function checkToTableIsSelf(item) {
                var t = methods.getTableByItem(er, item);
                if (tObject != t) {
                    return false;
                }
                return true;
            }
        },
        //获取窗体相关的出线
        getFromLinesByTable: function (er, args) {
            var table = args;
            var tObject = methods.getTableObject(er, table);
            var lines = methods.getLinesByTable(er, table);
            if (lines) {
                var temp = [];
                for (var i = 0; i < lines.length; i++) {
                    var l = lines[i];
                    var toItem = l.toItem;
                    if (checkToTableIsSelf(toItem.target)) {
                        temp.push(l);
                    }
                }
                return temp;
            }
            return [];
            function checkToTableIsSelf(item) {
                var t = methods.getTableByItem(er, item);
                if (tObject != t) {
                    return false;
                }
                return true;
            }
        },
        //获取所有的表
        getAllTables: function (er, args) {
            return er.data("windows");
        },
        //获取ITEM所在的窗体对象
        getTableByItem: function (er, args) {
            var item = args;
            if (item) {
                try {
                    var w = item.data("window");
                    return w.data("windowObject");
                }
                catch (ex) {
                }
            }
            return null;
        },
        //获取所有的线对象
        getAllLines: function (er, args) {
            var temp = [];
            var wins = methods.getAllTables(er);
            for (var i = 0; i < wins.length; i++) {
                var win = wins[i];
                var lines = methods.getLinesByTable(er, win);
                for (var n = 0; n < lines.length; n++) {
                    var line = lines[n];
                    if ($.inArray(line, temp) < 0) {
                        temp.push(line);
                    }
                }
            }
            return temp;
        },
        getItemsByTable: function (er, args) {
            var table = args;
            var items = [];
            table.find(".item").each(function (i, el) {
                items.push($.data(el, "itemObject"));
            });
            return items
        },
        //获取项对象
        getItemObject: function (er, args) {
            if (args) {
                var item = args;
                return item.data("itemObject");
            }
            return null;
        },
        //通过fieldId获取一个项对象
        getItemByFieldId: function (er, args) {
            if (args) {
                var win = args.table;
                var fieldId = args.fieldId;
                var box = win || er;
                var item = box.find("DIV.item[fieldId='" + fieldId + "']");
                if (item.length > 0) {
                    return item;
                }
            }
            return null;
        },
        //通过fieldname获取一个项对象
        getItemByFieldName: function (er, args) {
            if (args) {
                var win = args.table;
                var fieldName = args.fieldName;
                var box = win || er;
                var item = box.find("DIV.item[field='" + fieldName + "']");
                if (item.length > 0) {
                    return item.eq(0);
                }
            }
            return null;
        },
        //删除所有的线
        removeAllLine: function (er, args) {
            var lines = methods.getAllLines(er);
            $.loop(lines, function (v, i) {
                var fitem = v.fromItem;
                var titem = v.toItem;
                removeLine(er, { fromItem: fitem.target, toItem: titem.target });
            });
            var context = getCanvasContext(er);
            mappingLines(er, context, [], true);
        },
        //删除一根线
        removeLine: function (er, args) {
            var line = args;
            var fitem = line.fromItem.target;
            var titem = line.toItem.target;
            removeLine(er, { fromItem: fitem, toItem: titem });
            var lines = methods.getAllLines(er);
            var context = getCanvasContext(er);
            mappingLines(er, context, lines, true);
        },
        //删除一个窗口
        removeTable: function (er, args) {
            var win = args;
            win.window("close");
        },
        //改变控件尺寸
        resize: function (er, args) {
            var w = args.width;
            var h = args.height;
            var options = methods.options(er);
            if ($.support.boxModel) {
                w -= (options.borderWidth * 2);
                h -= (options.borderWidth * 2);
            }
            er.width(w).height(h);
            er.data("canvasSize", { width: w, height: h });
            var canvas = getCanvas(er);
            var canvasTemp = getCanvas(er, true);
            if (canvas.width() < w) {
                canvas.attr({ "width": w });
                canvasTemp.attr({ "width": w });
            }
            if (canvas.height() < h) {
                canvas.attr({ "height": h });
                canvasTemp.attr({ "height": h });
            }
            var context = getCanvasContext(er);
            var lines = methods.getAllLines(er);
            mappingLines(er, context, lines, true);
        },
        //选中项
        itemSelected: function (er, args) {
            var item = args;
            var itemObject = methods.getItemObject(er, item);
            if (itemObject) {
                itemObject.checked = true;
                item.find("INPUT[type=checkbox]").attr("checked", "checked");
            }
        },
        //取消项
        itemUnSelected: function (er, args) {
            var item = args;
            var itemObject = methods.getItemObject(er, item);
            if (itemObject) {
                itemObject.checked = false;
                item.find("INPUT[type=checkbox]").removeAttr("checked", "checked");
            }
        },
        getSelectedItems: function (er, args) {
            var table = args.table;
            var checkbox = table.find("input:checked");
            var items = [];
            checkbox.each(function (i, el) {
                var item = $(el.parentNode);
                item = methods.getItemObject(er, item);
                items.push(item);
            });
            return items;
        },
        //设置窗体标题
        setTitle: function (er, args) {
            var win = args.table;
            var title = args.title;
            win.window("setTitle", title);
            var obj = methods.getTableObject(er, win);
            obj.title = title;
        },
        updateField: function (er, args) {
            var item = args;
            item = methods.getItemObject(er, item);
            createItemInnerHTML(er, item);
        },
        setFields: function (er, args) {
            var table = args.table;
            var fields = args.items || [];
            if (table) {
                var lines = methods.getLinesByTable(er, table);
                var alllines = methods.getAllLines(er);
                var temp = [];
                for (var i = 0; i < alllines.length; i++) {
                    var line = alllines[i];
                    if ($.inArray(line, lines) < 0 && $.inArray(line, temp) < 0) {
                        temp.push(line);
                    }
                }
                var context = getCanvasContext(er);
                clearCanvas(context);
                mappingLines(er, context, temp, false);

                var temp2 = [];
                for (var i = 0; i < lines.length; i++) {
                    var l = lines[i];
                    var fi = l.fromItem;
                    var ti = l.toItem;
                    var obj = { line: l, fid: fi.fieldId, tid: ti.fieldId };
                    temp2.push(obj);
                    removeLine(er, { fromItem: fi.target, toItem: ti.target });
                }
                addItem(er, table, fields);
                for (var i = 0; i < temp2.length; i++) {
                    var obj = temp2[i];
                    var titem = er.find("DIV.item[fieldid=" + obj.tid + "]");
                    var fitem = er.find("DIV.item[fieldid=" + obj.fid + "]");
                    if (titem.length > 0 && fitem.length > 0) {
                        var l = addLine(er, context, fitem, titem);
                        var l2 = $.extend({}, l);
                        $.extend(l, obj.line, l2);
                    }
                }
                var listbox = table.find(".itemBox");
                listbox.width("100%")
                //listbox.width(listbox.parent().width());
                var items = table.find(".item");
                items.width(listbox.parent().width());
                if ($.support.boxModel) {
                    var w1 = items.width();
                    var w2 = items.outerWidth();
                    var w3 = w2 - w1;
                    items.width(w1 - w3);
                }
            }
        },
        setMainTable: function (er, args) {
            var ts = er.er("getAllTables");
            for (var i = 0; i < ts.length; i++) {
                var w = er.er("getTableObject", ts[i]);
                if (w) {
                    w.isMain = false;
                }
                var hear = w.target.window("header");
                var icon = hear.find(".panel-icon");
                icon.removeClass("icon-tip");
                //icon.addClass("icon-mydesktop");
                if (icon.data("oldICON")) {
                    icon.addClass(icon.data("oldICON"));
                    var options = w.target.window("options");
                    options.iconCls = icon.data("oldICON");
                }
            }
            var table = methods.getTableObject(er, args.table);
            if (table) {
                table.isMain = true;
                var hear = table.target.window("header");
                var icon = hear.find(".panel-icon");
                var classlist = icon.attr("class").split(" ");
                var temp = [];
                for (var i = 0; i < classlist.length; i++) {
                    if (classlist[i] && classlist[i].indexOf("icon-") == 0) {
                        temp.push(classlist[i]);
                    }
                }
                for (var i = 0; i < temp.length; i++) {
                    icon.removeClass(temp[i]);
                }
                icon.data("oldICON", temp.join(" "));
                icon.addClass("icon-tip");
                var options = table.target.window("options");
                options.iconCls = "icon-tip";
            }
        },
        getLineRelation: function (er, args) {
            var value = { "from": {}, "to": {} };
            var line = args;
            var from = line.fromItem;
            var to = line.toItem;
            var ft = er.er("getTableByItem", from.target);
            var tt = er.er("getTableByItem", to.target);
            value.from.table = ft;
            value.from.item = from;
            value.to.table = tt;
            value.to.item = to;
            return value;
        },
        getMainTable: function (er, args) {
            var ts = er.er("getAllTables");
            for (var i = 0; i < ts.length; i++) {
                var w = er.er("getTableObject", ts[i]);
                if (w && w.isMain) {
                    return w;
                }
            }
            return null;
        }
    };
});